/*
 * Utils.java
 *
 * Created on October 11, 2006, 11:24 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package keitykla;

import java.io.*;
import java.lang.*;
import java.util.*;
import javax.microedition.lcdui.*;

/**
 *
 * @author Ramunas
 */

public class Utils 
{
    public static long number = 0;
    
    /** Creates a new instance of Utils */
    public Utils() 
    {
    }
    
    public static String changeCurrency(String amount)
    {
        Currency cur = (Currency)Screens.getSetHashtable().getTable().get(Settings.getToCurrency());
        Currency curr = (Currency)Screens.getSetHashtable().getTable().get(Settings.getFromCurrency());
       //---------- Sutvarkysiu rate To ir quantity To -----------------------
        String rate_to = rateDivisionQuantity(cur);
        long return_comma = commaPlace(cur.getRate()) + cur.getQuantity().length() - 1 + number - commaPlace(rate_to);
        rate_to = returnComma(rate_to, return_comma);
       //-------- Sutvarkysiu rate From ir quantity From ---------------------
        String rate_from = rateDivisionQuantity(curr);
        return_comma = commaPlace(curr.getRate()) + curr.getQuantity().length() - 1 + number - commaPlace(rate_from);
        rate_from = returnComma(rate_from, return_comma);  
       //-------- Sutvarkysiu rate To ir rate From ---------------------------        
        String rate = rateDivisionRate(rate_to, rate_from);
        return_comma = commaPlace(rate_from) - commaPlace(rate_to) + number;
        rate = returnComma(rate, return_comma);
       //-------- Sutvarkysiu rate ir Amount ---------------------------------        
        String multiplication = multiplication(rate, amount);
        return_comma = (long)commaPlace(rate) + (long)commaPlace(amount);
        multiplication = returnComma(multiplication, return_comma);
        
        return finalResult(multiplication);
    }
    
    
//----------------------------------------------------------------------------        
    
     public static String getDateTime()
     {
	Calendar now = Calendar.getInstance();
        String month = numberOf2Digits(now.get(Calendar.MONTH));
        int hour = now.get(Calendar.HOUR_OF_DAY);
        int monthh = Integer.parseInt(month)+1;
        String date = now.get(Calendar.YEAR)	+ "."	+ monthh+ "."	+
			numberOf2Digits(	now.get(Calendar.DATE))+ " "+ hour +":"+now.get(Calendar.MINUTE);
	return	now.get(Calendar.YEAR)	+ "."	+ numberOf2Digits(now.get(Calendar.MONTH))+ "."	+
			numberOf2Digits(	now.get(Calendar.DATE))+ " "+ hour +":"+now.get(Calendar.MINUTE);
	}

//----------------------------------------------------------------------------    
     
    private static String numberOf2Digits(int i)
    {
        return (i < 10 ? "0" : "") + i;
    }
    
//----------------------------------------------------------------------------
    
    public static String getTime()
    {
	Calendar now = Calendar.getInstance();       
        int hour = now.get(Calendar.HOUR_OF_DAY);      
        String date = " "+hour +":"+now.get(Calendar.MINUTE);
        return	" "+hour +":"+now.get(Calendar.MINUTE);
    }
    
//----------------------------------------------------------------------------
    public static String getDate()
    {
	Calendar now = Calendar.getInstance();        
        String month = numberOf2Digits(now.get(Calendar.MONTH));        
        int monthh = Integer.parseInt(month)+1;  
			numberOf2Digits(	now.get(Calendar.DATE));
        return	now.get(Calendar.YEAR)	+ "."	+ monthh+ "."	+
			numberOf2Digits(	now.get(Calendar.DATE));        
    }
    
//-----------------------------------------------------------------------------    
    
    public static String calcNumKeys(String ss)
    {
	char[] cc=ss.toCharArray();
	String s="";
	int commaPos=ss.indexOf(',');
        if(commaPos ==-1)
            commaPos=ss.indexOf('.');
	for (int i = 0; i < cc.length; i++)
	{
	    cc[i]=Character.toUpperCase(cc[i]);
	    if(cc[i]>0x5A)
		continue;
	    if((cc[i]==' ' && commaPos==-1) || (commaPos==i && cc[i]==',') || (commaPos==i && cc[i]=='.'))
	    {
		s+=',';
		continue;
	    }
	    if(/*cc[i]=='.' || cc[i]==',' || */cc[i]=='0')
	    {
		s+=cc[i];
		continue;
	    }
	    if(cc[i]>=0x30 && cc[i]<=0x39)
	    {
		s+=cc[i];
		continue;
	    }
	    if(cc[i]=='-')
		continue;
	    int ci=cc[i]-0x41;
	    if(ci<0)
		continue;
	    int cid=2+ci/3;
	    if(cid>9)
		cid=9;
	    s+=cid;
	}
	return s;
    }
   
//----------------------------------------------------------------------------
    
    public static String returnComma(String rate, long return_comma )
    {
        int comma_place = commaPlace(rate);
        String rate_without_comma = withoutComma(rate);
        return_comma = return_comma + (long)comma_place;
        if(return_comma < 0) // stumsim kableli i desine puse
        {
            String temp = "";
            for(int i = 0; i < return_comma*(-1); i++)
                temp = temp + "0";
            rate = rate_without_comma + temp;
        }
        else
            if(return_comma > 0) // stumsim kableli i kaire puse
            {
                if(return_comma < rate_without_comma.length())
                {
                    long place = (long)rate_without_comma.length() - return_comma;
                    rate = rate_without_comma.substring(0, (int)place) + "." +rate_without_comma.substring((int)place);
                }
                else
                    if(return_comma > rate_without_comma.length())
                    {
                        long place = return_comma - (long)rate_without_comma.length();
                        String temp = "";
                        for(int i = 0; i < place; i++)
                            temp = temp + "0";
                        rate = "0." + temp + rate_without_comma;
                    }
                    else
                        if(return_comma == rate_without_comma.length())
                        {
                            rate = "0." + rate_without_comma;
                        }
            }
            else
                if(return_comma == 0) // jei 125
                {
                    rate = rate_without_comma;
                }
        
       return rate;
    }
    
//-----------------------------------------------------------------------------    
    
    private static String withoutComma(String rate)
    {
        int idx = 0;
        int comma_place = 0;
        if(rate.indexOf(".")!=-1 || rate.indexOf(",")!=-1)                  
        {
            if(rate.indexOf(".") > -1)
                idx = rate.indexOf(".");
            else
                idx = rate.indexOf(",");
            comma_place = rate.length()-idx;        // kiek skaiciu po kablelio
            rate = rate.substring(0,idx)+rate.substring(idx+1);
        }
        return rate;
    }
    
//-----------------------------------------------------------------------------
    
    public static int commaPlace(String rate)
    {
        boolean go = true;
        while(go)
        {
            String check = rate.substring(rate.length()-1);
            if(check.equals("0"))
                rate = rate.substring(0, rate.length()-1);
            else
                go = false;
        }
        int idx = 0;
        int comma_place = 0;
        if(rate.indexOf(".")!=-1 || rate.indexOf(",")!=-1)                  
        {
            if(rate.indexOf(".") > -1)
                idx = rate.indexOf(".");
            else
                idx = rate.indexOf(",");
            comma_place = rate.length()-idx;        // kiek skaiciu po kablelio
            rate = rate.substring(0,idx)+rate.substring(idx+1);
                                           
        }
        if(comma_place != 0)
            comma_place = comma_place - 1;
        return comma_place;
    }
        
//----------------------------------------------------------------------------
    
    public static ChoiceGroup getGroup(Currency cur)
    {
       String new_code = cur.getCode()+" "+cur.getName();
       ChoiceGroup to = Screens.getList();
       try
       {
           if(to.size() == 0)   // jei listas tuscias
           {
                if(cur.getChanged().equals("0"))
                    to.insert(0, new_code, null);
                else
                    to.insert(0, new_code, Image.createImage("/hand_2.png"));  // irasau pirma liesto irasa
           }
           else
               if(to.size() == 1 && to.getString(0).substring(0, 3).hashCode() < cur.getCode().hashCode())  // jei liste vienas irasas, ir reikia irasyti po jo
                   if(cur.getChanged().equals("0"))
                       to.insert(1, new_code, null);
                   else
                       to.insert(1, new_code, Image.createImage("/hand_2.png"));
               else
                   if(to.size() == 1 && to.getString(0).substring(0, 3).hashCode() > cur.getCode().hashCode()) // jei liste vienas irasas, ir reikia irasyti pries ji
                       if(cur.getChanged().equals("0"))
                           to.insert(0, new_code, null);
                       else
                           to.insert(0, new_code, Image.createImage("/hand_2.png"));
                   else
                       if(to.size() > 1 && to.getString(to.size()-1).substring(0, 3).hashCode() < cur.getCode().hashCode())
                           if(cur.getChanged().equals("0"))
                               to.append(new_code, null); // i pati gala
                           else
                               to.append(new_code, Image.createImage("/hand_2.png")); 
                       else
                           for(int i = 0; i < to.size(); i++)
                           {
                               if(to.getString(i).substring(0, 3).hashCode() > cur.getCode().hashCode())
                               {
                                   if(cur.getChanged().equals("0"))
                                       to.insert(i, new_code, null);
                                   else
                                       to.insert(i, new_code, Image.createImage("/hand_2.png"));
                                   i = to.size();
                               }
                            }
       }
       catch (IOException ex)
       {
           ex.printStackTrace();
       } 
        return to;
    }
       
//----------------------------------------------------------------------------
    
    public static String rateDivisionQuantity(Currency cur)
    {
        String result = "";
        long length = 0;        
        int rate_comma_place = commaPlace(cur.getRate());
        int quantity_comma_place = commaPlace(cur.getQuantity());
        long rate_without_comma = Long.parseLong(withoutComma(cur.getRate()));
        long quantity = Long.parseLong(cur.getQuantity());
        if(quantity > rate_without_comma)
        {   
            String quantity_ = "" + quantity;
            String rate_without_comma_ = "" + rate_without_comma;
            if(quantity_.length() == rate_without_comma_.length())
                length = 1 + 2;
            else
                length = quantity_.length() - rate_without_comma_.length() + 2;
            for(int i = 0; i < length; i++)
                rate_without_comma = rate_without_comma * 10;
            number = length;
        }
        long div = rate_without_comma / quantity;
        long mod = rate_without_comma % quantity;
        result = divAndMod(div, mod);
        
        return result;
    }
    
//----------------------------------------------------------------------------
    
    public static String rateDivisionRate(String rate_to, String rate_from)
    {
        String after_division = "";
        long comma_place_to = commaPlace(rate_to);
        long to_without_comma = Long.parseLong(withoutComma(rate_to));
        long comma_place_from = rate_from.length() - 1;
        long from_without_comma =Long.parseLong(withoutComma(rate_from));
        String to_without_comma1 = "" + to_without_comma;
        String from_without_comma1 = "" + from_without_comma;
        if(from_without_comma < to_without_comma)
        {
            long length = 0;
            if(to_without_comma1.length() == from_without_comma1.length()) // jei 160 (ilgis 3 skaitmenys) == 150 (ilgis 3 skaitmenys)
                length = 1 + 3; 
            else
                length = to_without_comma1.length() - from_without_comma1.length() + 3; // jei 16052 (ilgis 5 skaitmenys) > 150 (ilgis 3 skaitmenys)
            for(int i = 0; i < length; i++)
                from_without_comma = from_without_comma * 10;
            number = length;
        }
        long div = from_without_comma / to_without_comma;
        long mod = from_without_comma % to_without_comma;
        after_division = divAndMod(div, mod);
      
        return after_division;
    }  
    
//----------------------------------------------------------------------------
    
    private static String divAndMod(long div, long mod)
    {
        String result = "";
        if(mod != 0 && div != 0)
            result = "" + div +"."+ mod;        
        else 
            if(div != 0)
                result = "" + div;
            else
                if(mod != 0)
                    result = "0." + mod;        
        return result;
    }
    
//----------------------------------------------------------------------------
    
    private static String multiplication(String rate, String amount)
    {
        rate = withoutComma(rate);
        amount = withoutComma(amount);
        long multiplication = Long.parseLong(rate) * Long.parseLong(amount);
        
        return ""+multiplication;        
    }
    
//----------------------------------------------------------------------------
    
    public static String finalResult(String result)
    {
        int comma = commaPlace(result);
        if(comma != -1) // jei kablelis yra
        {
            if(comma > 4) // jei 2.25252
                result = result.substring(0,result.indexOf(".") + 5);
            else
                if(comma > 0 && comma < 5)// jei 0.2
                {
                    int how_much = 4 - comma;
                    for(int i = 0; i < how_much; i++)
                        result = result + "0";
                }
        }
        
        return result;
    }
    
    
    
    
}    
    